<template>
  <div class="box">
    <el-form ref="ruleFormRef" :model="form" :rules="rules" label-position="top" :inline="true">
      <el-form-item
        class="page-list"
        label="项目名称："
        label-width="80"
        required
        prop="projectName"
      >
        <el-input v-model="form.projectName" disabled placeholder="请选择" />
        <el-button
          :disabled="title.includes('详情')"
          class="choose-btn"
          @click="handleProject"
          type="primary"
          >选择项目</el-button
        >
      </el-form-item>
      <el-form-item label="项目开始时间：" required>
        <el-date-picker
          v-model="form.startTime"
          value-format="YYYY-MM-DD"
          type="date"
          placeholder="关联项目信息"
          clearable
          disabled
        />
      </el-form-item>
      <el-form-item label="项目结束时间：" required>
        <el-date-picker
          v-model="form.endTime"
          value-format="YYYY-MM-DD"
          type="date"
          placeholder="关联项目信息"
          clearable
          disabled
        />
      </el-form-item>
      <el-form-item label="项目负责人：" required>
        <el-input
          v-if="!title.includes('详情')"
          placeholder="关联项目信息"
          disabled
          v-model="form.projectLeaderName"
        />
        <el-input v-else placeholder="关联项目信息" disabled v-model="form.projectLeader" />
      </el-form-item>
      <el-form-item label="所属单位：" required>
        <el-input
          v-if="!title.includes('详情')"
          placeholder="关联项目信息"
          disabled
          v-model="form.affiliatedUnitName"
        />
        <el-input v-else placeholder="关联项目信息" disabled v-model="form.affiliatedUnit" />
      </el-form-item>
      <el-form-item label="合同编号：" required prop="contractNumber">
        <!-- <SelectOption
          :disabled="title == '项目验收详情'"
          v-model="form.contractNumber"
          :options="contractList"
          @changeValue="changeContract"
        ></SelectOption> -->
        <el-select
          :disabled="title.includes('详情')"
          v-model="form.contractNumber"
          placeholder="请选择"
          @change="changeContract"
          no-data-text="暂无关联合同"
        >
          <el-option
            v-for="item in contractList"
            :key="item.contractNumber"
            :label="item.contractNumber"
            :value="item.contractNumber"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="合同金额(万元)：" required>
        <el-input placeholder="关联合同信息" type="number" disabled v-model="form.contractAmount" />
      </el-form-item>
      <el-form-item class="textarea" label="申请验收说明：" required prop="requestInstructions">
        <el-input
          :disabled="title.includes('详情')"
          type="textarea"
          :rows="7"
          maxlength="512"
          show-word-limit
          v-model="form.requestInstructions"
        />
      </el-form-item>
      <el-form-item label="验收材料移交:" style="width: 100%">
        <el-upload
          ref="uploadRef"
          :limit="5"
          :disabled="title.includes('详情')"
          :headers="headers"
          v-model:file-list="attachmentFile"
          action="/fastDfs/file/upload"
          :on-success="handleAttachment"
          :on-preview="previewAttachment"
          :on-remove="removeAttachment"
          :on-exceed="handleExceed"
          :on-error="handleError"
        >
          <el-button :disabled="title == '项目验收详情'" type="primary">点击上传</el-button>
        </el-upload>
      </el-form-item>
    </el-form>
    <el-dialog v-model="data.projectDialog" width="60%" title="选择申请项目">
      <ProjectTable
        ref="projectDialogRef"
        v-if="data.projectDialog"
        @getProject="selectProject"
        :has-leader="true"
      ></ProjectTable>
      <template #footer>
        <el-button @click="data.projectDialog = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import { ElMessage } from 'element-plus'
import { defineComponent, reactive, ref, watch } from 'vue'
import { useStore } from 'vuex'
import ProjectTable from '@/views/project/components/ProjectTable/index.vue'
import SelectOption from '@/views/project/components/selectOption/index.vue'
import { getContractList } from '@/views/project/api/commom'
import { ergodicListName, type } from '@/utils/utils'

export default defineComponent({
  components: {
    SelectOption,
    ProjectTable,
  },
  props: {
    title: {
      type: String,
      default: '',
    },
  },
  setup(props) {
    const data = reactive({
      projectDialog: false,
      filePathArray: [] as any,
      fileNameArray: [] as any,
    })
    const store = useStore()
    const rules = reactive({
      projectName: { required: true, message: '请选择项目' },
      contractNumber: { required: true, message: '请选择项目关联合同' },
      requestInstructions: { required: true, message: '请填写验收说明' },
    })
    const form = store.state.projectCenter.applicationForm
    form.applyPerson = JSON.parse(localStorage.getItem('userInfo') as any).userId
    const ruleFormRef = ref()
    const contractList = ref([]) as any
    form.status = 0
    form.checkType = '项目验收'
    const handleProject = () => {
      data.projectDialog = true
    }
    const projectDialogRef = ref()
    const selectProject = (row) => {
      console.log(row,'selectProject');
      data.projectDialog = false
      form.projectId = row.id
      form.projectName = row.projectName
      form.projectNumber = row.id
      form.startTime = row.startTime
      form.endTime = row.endTime
      form.projectLeader = row.projectLeader
      form.projectLeaderName = row.projectLeaderName
      form.affiliatedUnit = row.affiliatedUnit
      form.affiliatedUnitName = row.affiliatedUnitName
      form.projectCategory = row.projectCategory
    }
    const changeContract = (obj) => {
      console.log(obj, 'changeContract')
      // form.contractName = obj.contractName
      form.contractNumber = obj
      // form.contractAmount = obj.contractAmount
      form.contractName = ergodicListName(obj, contractList.value, 'contractNumber', 'contractName')
      form.contractAmount = ergodicListName(
        obj,
        contractList.value,
        'contractNumber',
        'contractAmount'
      )
      console.log(form.contractName, form.contractAmount, 'asdasdasd')
    }
    watch(
      () => form.projectNumber,
      () => {
        form.contractNumber = ''
        getContractList(form.projectId).then((res) => {
          console.log(res.data.data, 'getContractList')
          contractList.value = res.data.data
          if (contractList.value.length == 0) {
            ElMessage({
              message: '该项目暂无关联合同',
              type: 'warning',
            })
          }
        })
      }
    )
    const handleAttachment = (uploadFile) => {
      if (uploadFile.code == 200) {
        ElMessage({
          message: '上传成功',
          type: 'success',
        })
        data.filePathArray.push(uploadFile.data.path)
        data.fileNameArray.push(uploadFile.data.fileName)
      } else {
        ElMessage({
          message: '上传失败',
          type: 'error',
        })
      }
    }
    let attachmentFile = []
    if (form.checkFilePath.length > 0) {
      attachmentFile = type(form.checkFilePath)
        ? JSON.parse(form.checkFileName).map((item, index) => {
            return {
              name: item,
              url: JSON.parse(form.checkFilePath)[index],
            }
          })
        : []
    }
    console.log(attachmentFile, 'attachmentFile申请')
    const previewAttachment = (uploadFile) => {
      console.log(uploadFile, 'uploadFile')
      if (props.title.includes('详情')) {
        window.open(uploadFile.url)
      } else {
        window.open(uploadFile.response.data.path)
      }
    }
    const removeAttachment = (file, uploadFiles) => {
      console.log(uploadFiles, 'uploadFiles')
      data.filePathArray = uploadFiles.map((fileItem) => {
        return fileItem.response.data.path
      })
      data.fileNameArray = uploadFiles.map((fileItem) => {
        return fileItem.response.data.fileName
      })
    }
    const handleExceed = () => {
      ElMessage({
        message: '最多上传5个附件',
        type: 'wraning',
      })
    }
    const handleError = () => {
      ElMessage({
        message: '上传失败',
        type: 'error',
      })
    }
    const submitForm = async () => {
      form.checkFilePath = JSON.stringify(data.filePathArray)
      form.checkFileName = JSON.stringify(data.fileNameArray)
      return new Promise((resolve, reject) => {
        ruleFormRef.value.validate((valid) => {
          console.log(valid, 'valid')
          if (valid) {
            resolve('校验成功')
          } else {
            ElMessage({
              message: '请将基本信息补充完整',
              type: 'warning',
            })
            reject('校验失败')
          }
        })
      })
    }

    const cookie = () => localStorage.getItem('token')
    return {
      data,
      form,
      projectDialogRef,
      store,
      rules,
      ruleFormRef,
      contractList,
      attachmentFile,
      headers: {
        Authorization: 'Bearer ' + cookie(),
      },
      submitForm,
      handleProject,
      selectProject,
      changeContract,
      handleAttachment,
      previewAttachment,
      removeAttachment,
      handleExceed,
      handleError,
    }
  },
  beforeUnmount() {
    console.log('beforeUasdasdnmount')
    for (let key in this.form) {
      this.form[key] = ''
    }
  },
})
</script>
<style lang="scss" scoped>
.el-form-item {
  width: 23%;
}
.textarea {
  width: 95%;
}
/deep/.el-form-item--small .el-form-item__label {
  line-height: 20px;
}
.page-list {
  width: 47%;
  .choose-btn {
    margin-left: 10px;
  }
}
:deep(.el-upload-list__item.is-success.focusing .el-icon-close-tip) {
  display: none !important;
}
</style>
